import { writable } from 'svelte/store';
import { v4 as uuidv4 } from 'uuid';

interface Toast {
  type: string;
  id: string;
  message: string;
}

const toasts = writable<Toast[]>([]);

function addToast(message: string, type = 'info', duration = 3000) {
  const id = uuidv4();

  toasts.update((allToasts: Toast[]) => {
    return [...allToasts, { type, id, message }];
  });

  setTimeout(() => {
    removeToast(id);
  }, duration);
}
function removeToast(id: string) {
  toasts.update((allToasts: Toast[]) => {
    return allToasts.filter(toast => toast.id !== id);
  });
}

export {
  toasts,
  addToast,
  removeToast,
};
